﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TechnicBlog.Models;

namespace TechnicBlog.Controllers.UserManager
{
    public class UserController : Controller
    {
        //
        // GET: /User/

        public ActionResult Index()
        {
            return View();
        }

        public string List()
        {
            DBContext db = new DBContext();
            int pageindex = Convert.ToInt32(Request.Form["page"]);
            int pagesize = Convert.ToInt32(Request.Form["rows"]);
            string userName = "";
            string userLoginName = "";
            if (Request.QueryString["UserName"] != null)
                userName = Request.QueryString["UserName"].ToString();
            if (Request.QueryString["UserLoginName"] != null)
                userLoginName = Request.QueryString["UserLoginName"].ToString();
                IList<UserEntity> list = db.Users.ToList();
            var result = from u in list
                         orderby u.CreateTime descending
                         where u.UserName.Contains(userName)
                         where u.LoginName.Contains(userLoginName)
                         select u;
            List<UserEntity> l = (result).Skip(pagesize * (pageindex - 1)).Take(pagesize).ToList();
            int total = result.Count();
            Newtonsoft.Json.Converters.IsoDateTimeConverter timeConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
            //这里使用自定义日期格式，如果不使用的话，默认是ISO8601格式           
            timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
            //jsonObject是准备转换的对象
            string s = "{\"total\":" + total + ",\"rows\":" + Newtonsoft.Json.JsonConvert.SerializeObject(l, Newtonsoft.Json.Formatting.Indented, timeConverter) + "}";
            db.Dispose();
            return s;
        }

        public ActionResult Create(UserEntity model)
        {
            //IList<UserRemark> list = new List<UserRemark>();
            //list.Add(new UserRemark());
            //model.remarks = list;
            return View(model);
        }

        public ActionResult Add(UserEntity model)
        {
            try
            {
                DBContext db = new DBContext();
                model.CreateTime = DateTime.Now;
                //model.UserRemark.UserId = 1;
                //db.Remark.Add(model.UserRemark);
                //db.SaveChanges();
                //IList<UserRemark> list = new List<UserRemark>();
                //list.Add(new UserRemark() { Remark = Request.Form["Remark"] });
                //model.remarks = list;
                db.Users.Add(model);
                db.SaveChanges();
                db.Dispose();
                return JavaScript("$('#loading').window('close');$.messager.alert('提示','<br>恭喜您！新增成功！','info');TreeLink('User/Index', '用户列表');");
            }
            catch (Exception)
            {
                return JavaScript("$('#loading').window('close');$.messager.alert('错误','<br>新增失败！请检查输入是否有误！','error');");
            }
        }

        public ActionResult Delete(int id)
        {
            DBContext db = new DBContext();
            UserEntity model = db.Users.Find(id);
            if (model == null)
            {
                return JavaScript("$('#loading').window('close');$.messager.alert('提示','<br>要删除的数据不存在，或已被删除！','info'); $('#rptUserList').datagrid('reload');");
            }
            db.Users.Remove(model);
            db.SaveChanges();
            db.Dispose();
            return JavaScript("$('#loading').window('close');$.messager.alert('提示','<br>删除成功！','info');$('#rptUserList').datagrid('reload');");
        }

        public ActionResult Edit(int id)
        {
            DBContext db = new DBContext();
            UserEntity model = db.Users.Find(id);
            //IList<UserRemark> list = new List<UserRemark>();
            //list.Add(db.Remark.Single(r => r.UserId == id));
            //model.remarks = list;
            db.Dispose();
            if (model == null)
            {
                RedirectToAction("Index");
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(UserEntity model)
        {
            try
            {
                DBContext db = new DBContext();
                UserEntity user = db.Users.Find(model.UserId);
                //user.UserName = model.UserName;
                //UserRemark remark = db.Remark.Single(r => r.UserId == model.UserId);
                //remark = model.remarks[0];
                //UpdateModel(remark);
                UpdateModel(user);
                //user.remarks[0].Remark = model.remarks[0].Remark;
                //db.Users.Attach(model);
                //db.Entry<UserEntity>(model).State = System.Data.EntityState.Modified;
                db.SaveChanges();
                db.Dispose();
                return JavaScript("$('#loading').window('close');$.messager.alert('提示','<br>恭喜您！编辑成功！','info');TreeLink('User/Index', '用户列表');");
            }
            catch (Exception)
            {
                return JavaScript("$('#loading').window('close');$.messager.alert('错误','<br>编辑失败！请检查输入是否有误！','error');");
            }
        }

        public ActionResult Detail(int id)
        { 
            DBContext db = new DBContext();
            UserEntity model = db.Users.Find(id);
            db.Dispose();
            if (model == null)
            {
                RedirectToAction("Index");
            }
            return View(model);
        }
    }
}
